'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const u = require('../nodes/identity.cjs'),
  A = require('../nodes/Scalar.cjs'),
  p = require('./resolve-block-scalar.cjs'),
  L = require('./resolve-flow-scalar.cjs');
function d(s, a, e, o) {
  const {
      value: l,
      type: i,
      comment: r,
      range: c,
    } = a.type === 'block-scalar'
      ? p.resolveBlockScalar(a, s.options.strict, o)
      : L.resolveFlowScalar(a, s.options.strict, o),
    t = e
      ? s.directives.tagName(e.source, f => o(e, 'TAG_RESOLVE_FAILED', f))
      : null,
    S =
      e && t
        ? m(s.schema, l, t, e, o)
        : a.type === 'scalar'
          ? y(s, l, a, o)
          : s.schema[u.SCALAR];
  let n;
  try {
    const f = S.resolve(l, g => o(e ?? a, 'TAG_RESOLVE_FAILED', g), s.options);
    n = u.isScalar(f) ? f : new A.Scalar(f);
  } catch (f) {
    const g = f instanceof Error ? f.message : String(f);
    o(e ?? a, 'TAG_RESOLVE_FAILED', g), (n = new A.Scalar(l));
  }
  return (
    (n.range = c),
    (n.source = l),
    i && (n.type = i),
    t && (n.tag = t),
    S.format && (n.format = S.format),
    r && (n.comment = r),
    n
  );
}
function m(s, a, e, o, l) {
  var c;
  if (e === '!') return s[u.SCALAR];
  const i = [];
  for (const t of s.tags)
    if (!t.collection && t.tag === e)
      if (t.default && t.test) i.push(t);
      else return t;
  for (const t of i) if ((c = t.test) != null && c.test(a)) return t;
  const r = s.knownTags[e];
  return r && !r.collection
    ? (s.tags.push(Object.assign({}, r, { default: !1, test: void 0 })), r)
    : (l(
        o,
        'TAG_RESOLVE_FAILED',
        `Unresolved tag: ${e}`,
        e !== 'tag:yaml.org,2002:str',
      ),
      s[u.SCALAR]);
}
function y({ directives: s, schema: a }, e, o, l) {
  const i =
    a.tags.find(r => {
      var c;
      return r.default && ((c = r.test) == null ? void 0 : c.test(e));
    }) || a[u.SCALAR];
  if (a.compat) {
    const r =
      a.compat.find(c => {
        var t;
        return c.default && ((t = c.test) == null ? void 0 : t.test(e));
      }) ?? a[u.SCALAR];
    if (i.tag !== r.tag) {
      const c = s.tagString(i.tag),
        t = s.tagString(r.tag),
        S = `Value may be parsed as either ${c} or ${t}`;
      l(o, 'TAG_RESOLVE_FAILED', S, !0);
    }
  }
  return i;
}
exports.composeScalar = d;
